

import csv
from config import *
import redis, json,os,pymongo



# redis连接
pool = redis.ConnectionPool(**rConfig)
r = redis.Redis(connection_pool=pool)

# pymongo链接
mongo = pymongo.MongoClient(mongoClient)
db = mongo['taobao']

class Helper( object ):


    def __init__(self):

        pass

    #写入csv文件
    @staticmethod
    def csv_write( path,data):

        with open('{0}/完成结果.csv'.format( path ), mode='a+', encoding='gbk', newline='') as f:

            writer = csv.writer(f, dialect='excel')

            for row in data:

                writer.writerow(row)

            return True

    # 生成淘宝店铺任务任务
    @staticmethod
    def saveRedis( data ):

        r.lpush('tb_task', json.dumps(data, ensure_ascii=False))

        print('存储redis成功:',data['nick'])

    # 生成页码任务
    @staticmethod
    def savePage( keyword ):

        data = {'keyword':keyword}

        for i in range(0,1000,20):

            data['page'] = i

            r.lpush('shop_task',json.dumps( data,ensure_ascii=False ))

            print('关键词:%s\t生成%d页码任务成功'%(data['keyword'],i))\
    # 获取页码任务
    @staticmethod
    def getPage():

        t = r.rpop('shop_task')

        if t == None:

            return None

        else:

            n = json.loads(t)

            return n

    #获取redis长度
    @staticmethod
    def lenRedis( name ):


        length = r.llen( name )

        return length

    # 获取店铺信息采集任务
    @staticmethod
    def getRedis():

        t = r.lpop('tb_task')

        if  t == None:

            return None

        else:

            n = json.loads( t )

            return n

    #创建文件夹
    @staticmethod
    def writeRes( con ):

        date = time.strftime('%Y-%m-%d', time.localtime(time.time())).replace('-','')

        save_dir = date

        if not os.path.exists( save_dir ):

            os.mkdir(save_dir )

        Helper.csv_write(save_dir,con)

        print( con )

    #存储到pymongo
    @staticmethod
    def saveMongo( data  ):

        # try:

            db['phone'].update({'uid':data['uid']},{'$set':data},True)

            print('%s 存储到MongoDB成功'%data['title'])

        # except:
        #
        #     print('%s 存储到MongoDB失败'% data['title'])



if __name__ == '__main__':

   print( Helper.lenRedis('tb_task')<=0)



